import requests
from lxml import etree
import re, json
from multiprocessing.dummy import Pool


# 自定义无信息异常
class NoInfoError(Exception):
    pass


class AcquireInfoTotal(object):
    def __init__(self, pid):
        self.pid = pid
        get_params = {'id': str(pid)}

        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36"
        }

        url_get = "http://10.68.1.38:8000/doqleiview/doqleiview.aspx"

        self.users = requests.Session()

        get_basic_content = self.users.get(url_get, params=get_params, headers=self.headers)

        self.basic_html_doc = get_basic_content.text

        basic_tree = etree.HTML(self.basic_html_doc)

        self.basic_param_patient = basic_tree.xpath('//ul[@class="ztree"]')[0].attrib
        basic_param_code = basic_tree.xpath('//div[contains(@class, "model_menu_items")]')[0].attrib
        post_param_menu = {
            'type': self.basic_param_patient['data-type'],
            'mdata': self.basic_param_patient['data-mdata'],
            'integrationim': self.basic_param_patient['data-integrationim'],
            'inum': self.basic_param_patient['data-inum'],
            'idata[0].key': 'uhid',
            'idata[0].value': basic_param_code["data-uhid"],
            'idata[1].key': 'date_validated',
            'idata[1].value': self.basic_param_patient['data-date_validated'],
            'idata[2].key': 'treatment',
            'idata[2].value': basic_param_code["data-uhid"].split(']')[1],
        }
        url_menu = "http://10.68.1.38:8000/Menu/MedicalMenu"

        self.menu_json_data = self.users.post(
            url_menu,
            headers=self.headers,
            data=post_param_menu
        )

    def query_content(self, query_kind='病程记录'):
        menu_respond = self.menu_json_data.json()
        test_info_data = {}
        for i in menu_respond['Data']:

            test_info_data.update(i.setdefault('Data', {}))

            if i.setdefault('Text', '') == query_kind:
                mtype = i['Type']
                break
            if i.setdefault('Children', ''):
                for j in i['Children']:
                    test_info_data.update(j.setdefault('Data', {}))
                    if j.setdefault('Text', '') == query_kind:
                        mtype = j['Type']

                        break
                else:
                    continue
                break

        post_para_test = {
            'type': self.basic_param_patient['data-type'],
            'patientid': '☆',
            'snick': '',
            'mdata': self.basic_param_patient['data-mdata'],
            'integrationim': self.basic_param_patient['data-integrationim'],
            'inum': self.basic_param_patient['data-inum'],
            'patientname': self.basic_param_patient['data-patientname'],
            'official1': self.basic_param_patient['data-official1'],
            'mtype': mtype,
        }

        index_ = 0
        for k, v in test_info_data.items():
            post_para_test['idata[%s].key' % index_] = k
            post_para_test['idata[%s].value' % index_] = v
            index_ += 1

        url_result = "http://10.68.1.38:8000/Content/Index"

        result = self.users.post(
            url_result,
            headers=self.headers,
            data=post_para_test
        ).text

        return {query_kind: result}


class DataResolver(object):
    def __init__(self, pid):
        self.patient_info = {}
        self.pid = pid

    @staticmethod
    def do_table(html_grab):
        tree = etree.HTML(html_grab)
        tables = tree.xpath('//table')
        result_list = []
        for table in tables:
            table_dic = {}
            trs = table.findall('.//tr')
            table_dic['test_title'] = trs[0].find('.//td//input').attrib.get('value').split('(')[0]
            test_date = trs[0].find('.//td//input').attrib.get('value').split('(')[1]
            test_date = test_date.strip()
            test_date = test_date.strip(':')
            test_date = test_date.strip(')')
            table_dic['test_date'] = test_date
            table_dic['test_result'] = []
            for tr in trs[2:]:
                tds = tr.findall('.//td')
                result_details = {
                    'title': tds[1].text,
                    'result': tds[2].text.strip(),
                    'note': tds[3].find('./font').text,
                    'flag': '升高' if tds[3].find('./font').text == '↑' else (
                        '降低' if tds[3].find('./font').text == '↓' else '正常')
                }

                table_dic['test_result'].append(result_details)
            result_list.append(table_dic)
        return result_list

    @staticmethod
    def do_test(test_result):
        result_dic = {}
        with open('.\\myjson\\spliter.json', 'r', encoding='utf-8') as load_f:
            load_dic = json.load(load_f)

        for each_test_dic in test_result:

            for k_test in load_dic.keys():
                if k_test in each_test_dic["test_title"]:
                    for each_test_result in each_test_dic["test_result"]:
                        if k_test not in result_dic.keys():
                            result_dic[k_test] = {}
                        if each_test_dic["test_date"] not in result_dic[k_test].keys():
                            result_dic[k_test][each_test_dic["test_date"]] = []

                        for each_test_key in load_dic[k_test].keys():
                            if each_test_key in each_test_result["title"]:
                                if each_test_result["flag"] in load_dic[k_test][each_test_key].keys():
                                    result_dic[k_test][each_test_dic["test_date"]].append(
                                        {
                                            "项目": each_test_result["title"],
                                            "结果": "%s %s" % (each_test_result["result"],
                                                             load_dic[k_test][each_test_key]["单位"]),
                                            "提示": load_dic[k_test][each_test_key][each_test_result["flag"]]
                                        })

        with open('.\\myjson\\test_analysis.json', 'r', encoding='utf-8') as load_f:
            test_load = json.load(load_f)
        for each_test_dic in test_result:

            for k_test in test_load.keys():
                if k_test in each_test_dic["test_title"]:
                    for each_test_result in each_test_dic["test_result"]:
                        if k_test not in result_dic.keys():
                            result_dic[k_test] = {}
                        if each_test_dic["test_date"] not in result_dic[k_test].keys():
                            result_dic[k_test][each_test_dic["test_date"]] = []

                        for each_test_key_analysis in test_load[k_test].keys():
                            if each_test_key_analysis in each_test_result["title"]:

                                if each_test_result["result"] != test_load[k_test][each_test_key_analysis]:
                                    result_dic[k_test][each_test_dic["test_date"]].append(
                                        {
                                            "项目": each_test_result["title"],
                                            "结果": each_test_result["result"],
                                            "提示": ""
                                        })

        result_string = '入院根据当前疫情防控及上级文件要求：查新型冠状病毒核酸检测示阴性。'
        for each_test_kind, each_test_kind_v in result_dic.items():

            result_string += '查%s：' % each_test_kind

            for index_v, data_v in enumerate(each_test_kind_v.values()):
                if data_v:
                    if index_v > 0:
                        result_string += '查%s：' % each_test_kind
                    normal = True

                    for each_data_dict in data_v:

                        result_string += '%s：%s ' % (each_data_dict['项目'], each_data_dict['结果'])
                        if each_data_dict['提示']:
                            normal = False
                            result_string += '提示：%s' % each_data_dict['提示']
                    if normal and each_test_kind in load_dic.keys():
                        result_string += '未见明显异常。'
                else:
                    result_string += "未见异常。"

        return result_string

    def record_resolve(self, html_dic):
        tree = etree.HTML(html_dic['病程记录'])
        basic_info_td = tree.xpath('//div[@esttype="入院记录"]//table')[0].xpath('.//td//text()')
        for i in basic_info_td:
            i = i.strip()
            if i:
                info_list = i.split("：")
                self.patient_info[info_list[0]] = info_list[1]

        self.patient_info["住院号"] = str(self.pid)
        self.patient_info["入院日期"] = self.patient_info['入院时间'].split()[0]
        self.patient_info["主诉"] = tree.xpath('//span[@itemid="5"]')[0].text
        self.patient_info["诊断"] = tree.xpath('//span[@itemid="8"]')[0].xpath('string(.)').split()[1]
        self.patient_info["现病史"] = tree.xpath('//span[@itemid="6"]')[0].text
        self.patient_info["TPRBP"] = tree.xpath('//span[@itemid="10"]')[0].text
        self.patient_info["入院体检"] = tree.xpath('//p[@class="childmouseover"]')[0].xpath('string(.)').strip()
        self.patient_info["入院化验单"] = \
        tree.xpath('//p[@class="childmouseover"]/following-sibling::p/following-sibling::p//text()')[0]
        self.patient_info["病人简介"] = tree.xpath('//span[@itemid="1"]')[0].text
        first_info_p = tree.xpath('//div[@esttype="首次病程记录"]//p')[1].xpath('string(.)').strip()
        content_1 = re.findall(r".+病例特点：1(\.|、)(.+?)2(\.|、)(查体|体格检查).+?", first_info_p)
        if content_1:
            self.patient_info['病例特点'] = content_1[0][1]
        content_2 = re.findall(r".+诊疗计划：1(\.|、)(.+)2(\.|、)(.+)3(\.|、)(.+)4(\.|、)(.+)\d?", first_info_p)
        if content_2:
            self.patient_info['诊疗计划'] = content_2[0][1::2]

        lis_data = html_dic.setdefault('LIS报告单', '')
        if lis_data:
            result_lis = self.do_table(lis_data)

            result_lis = self.do_test(result_lis)

            self.patient_info['化验单'] = result_lis

        return self.patient_info


if __name__ == '__main__':
    a = AcquireInfoTotal(21028579)
    l = ['病程记录', 'LIS报告单']
    pool = Pool(3)
    result = pool.map(a.query_content, l)
    result_dic = {}
    for i in result:
        result_dic.update(i)
    b = DataResolver(a.pid)
    b.record_resolve(result_dic)
    print(b.patient_info)
